import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets


# 使用逻辑回归去预测
def plot_decision_boundary(model, axis):
    # 生成网格
    x0, x1 = np.meshgrid(
        np.linspace(axis[0], axis[1], int((axis[1] - axis[0]) * 100)).reshape(-1, 1),
        np.linspace(axis[2], axis[3], int((axis[3] - axis[2]) * 100)).reshape(-1, 1)
    )
    X_new = np.c_[x0.ravel(), x1.ravel()]  # 拼接起来
    y_predict = model.predict(X_new)
    zz = y_predict.reshape(x0.shape)
    from matplotlib.colors import ListedColormap
    custom_cmap = ListedColormap(['#EF9A9A', '#FFF59D', '#90CAF9'])
    plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)


iris = datasets.load_iris()

raw_X = iris.data
raw_y = iris.target

X = raw_X[raw_y < 2, :2]
y = raw_y[raw_y < 2]

plt.scatter(X[y == 0, 0], X[y == 0, 1], color="red")
plt.scatter(X[y == 1, 0], X[y == 1, 1], color="blue")
plt.show()

# 使用逻辑回归去预测
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=666)

from sklearn.linear_model import LogisticRegression

log_reg = LogisticRegression()
log_reg.fit(X_train, y_train)
score = log_reg.score(X_test, y_test)
print(f"计算分数：{score}")
print(log_reg.coef_)
print(log_reg.intercept_)

# 边界线
plot_decision_boundary(log_reg, axis=[2, 8, 0, 8])
plt.scatter(X[y == 0, 0], X[y == 0, 1])
plt.scatter(X[y == 1, 0], X[y == 1, 1])
plt.show()


#scikit-learn中的混淆矩阵，精准率和召回率
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score

y_log_predict=log_reg.predict(X_test)
f=confusion_matrix(y_test, y_log_predict)
print(f'混淆矩阵:{f}')

precision=precision_score(y_test, y_log_predict)
print(f'精准率:{precision}')
recall=recall_score(y_test, y_log_predict)
print(f'召回率:{recall}')
